import { reactive, ref, nextTick, readonly } from 'vue';
import _ from 'lodash';
import { Message } from '@arco-design/web-vue';
import { commonList } from '@/api/common/common';
// import { saveYaYData, submitDataOver } from '@/api/readPathology/readPathology';
import type { CommonListItem } from '@/api/common/common.d';
import type { CallBackData } from '@/components/dialog/type.d';
// import type * as Type from '@/api/readPathology/readPathology.d';
// import type * as Temp from './type.d';

interface CallBack {
  flag: boolean;
  status: string;
}

export default function useSubmit(arListData: any | null) {
  
  // 标记废片显示值
  const markScrapVisible = ref<boolean>(false);

  // 标记废片选项集合
  const scrapList = ref<CommonListItem[]>([]);

  // 标记废片选项值
  const scrapValue = ref<string>('');
  // 标记废片备注值
  const discardRemark = ref<string>('');

  // 提交显示值
  const submitVisible = ref(false);

  const seriesSetFormRef = ref();
  const showLesionList = ref();

  // 提交
  const handleSubmit = () => {
    submitVisible.value = true;
  };
  let tempType = '';
  // 提交弹窗事件
  const handleSubmitVisible = (data: CallBack) => {
    tempType = data.status;
    if (data.status === 'save') {
      // 单序列提交
      validateForm(data.flag);
    } else {
      // 多序列提交
      validateForm(data.flag);
    }
  };
  let currentIndex = 0;
  let seriesFormStatus = false;
  let mjorSignsFormStatus = false;
  // 校验表单
  const validateForm = async (flag: boolean) => {
    if (seriesSetFormRef.value) {
      // 处理大征象
      const seriesValidateRes = await seriesSetFormRef.value?.validate();
      if (seriesValidateRes === undefined) {
        seriesFormStatus = true;
        // 从病灶列表第一项开始依次聚焦来衔接小征象的校验
        submitVisible.value = flag;
        const showLesionListVal = showLesionList.value;
        // if (showLesionListVal.length) {
        //   const oneDisease = _.cloneDeep(
        //     showLesionListVal[currentIndex].disease
        //   );
        //   currentSubmenuItem.value = '';
        //   currentMiniSeriesSet.value = _.cloneDeep({
        //     formId: 0,
        //     formOptions: [],
        //     form: {},
        //   });
        //   currentSubmenuItem.value = oneDisease.id;
        //   currentMiniSeriesSet.value = _.cloneDeep(oneDisease.list);
        // }
        // 处理小征象
        nextTick(async () => {
          // const mjorSignsRes = await mjorSignsFormRef.value?.validate();
          // if (mjorSignsRes === undefined) {
          //   submitVisible.value = flag;
          //   _validateForm(currentIndex, flag);
          // } else {
          //   // 弹出错误信息
          //   Object.keys(mjorSignsRes).forEach((key) => {
          //     Message.error({
          //       content: `标注征象${mjorSignsRes[key].label}填写错误！`,
          //       closable: true,
          //       duration: 10000,
          //     });
          //   });
          //   submitVisible.value = flag;
          // }
        });
      } else {
        // 弹出错误信息
        Object.keys(seriesValidateRes).forEach((key) => {
          Message.error({
            content: `序列征象${seriesValidateRes[key].label}填写错误！`,
            closable: true,
            duration: 10000,
          });
        });
      }
      submitVisible.value = flag;
    }
  };

  // 校验小征象辅助函数
  const _validateForm = async (index: number, flag: boolean) => {
    if (index === showLesionList.value.length - 1) {
      mjorSignsFormStatus = true;
      submitVisible.value = flag;
      if (seriesFormStatus && mjorSignsFormStatus && tempType === 'save') {
        const params = {
          arIdList: arListData! && [arListData[0].id],
          status: 2,
        };
        // const res = await submitDataOver(params);
        Message.success('保存成功！');
        submitVisible.value = flag;
        setTimeout(() => {
          window.opener = null;
          window.open('', '_self');
          window.close();
        }, 1000);
      } else {
        if (arListData?.length && arListData?.length <= 1) {
          sectionVisible.value = true;
        } else {
          const params = {
            arIdList: arListData! && [arListData[0].id],
            status: 2,
          };
          // const res = await submitDataOver(params);
          Message.success('保存成功！');
          submitVisible.value = flag;
          arListData?.splice(0, 1)!;
          if (arListData?.length === 0) {
            sectionVisible.value = true;
          } else {
            setTimeout(() => {
              window.opener = null;
              window.open(window.location.href, '_self');
            }, 1000);
          }
        }
      }
      return;
    } else {
      index++;
    }
    // const showLesionListVal = showLesionList.value;
    // if (showLesionListVal.length) {
    //   const oneDisease = _.cloneDeep(showLesionListVal[index].disease);
    //   currentSubmenuItem.value = '';
    //   currentMiniSeriesSet.value = _.cloneDeep({
    //     formId: 0,
    //     formOptions: [],
    //     form: {},
    //   });
    //   currentSubmenuItem.value = oneDisease.id;
    //   currentMiniSeriesSet.value = _.cloneDeep(oneDisease.list);
    // }
    nextTick(async () => {
      // const mjorSignsRes = await mjorSignsFormRef.value?.validate();
      // if (mjorSignsRes === undefined) {
      //   _validateForm(index, flag);
      // } else {
      //   // 弹出错误信息
      //   Object.keys(mjorSignsRes).forEach((key) => {
      //     Message.error({
      //       content: `标注征象${mjorSignsRes[key].label}填写错误！`,
      //       closable: true,
      //       duration: 10000,
      //     });
      //   });
      //   submitVisible.value = flag;
      // }
    });
  };

  // 已无新切片弹窗显示值
  const sectionVisible = ref(false);

  // 无新切片点击事件
  const handleSectionVisible = (data: CallBackData) => {
    if (data.status === 'save') {
      data.done(true);
      sectionVisible.value = data.flag;
      setTimeout(() => {
        window.opener = null;
        window.open('', '_self');
        window.close();
      }, 1000);
    }
  };

  // 标记废片点击
  const handleMarkDesert = () => {
    initScrapData();
  };

  // 标记废片弹窗事件
  const handleMarkScrapVisible = async (data: CallBackData) => {
    if (data.status === 'save') {
      data.done(true);
      const params = {
        arIdList: arListData! && [arListData[0].id],
        status: 3,
        discardCode: scrapValue.value,
        discardRemark: discardRemark.value,
      };
      // const res = await submitDataOver(params);
      Message.success('保存成功！');
      markScrapVisible.value = data.flag;
      setTimeout(() => {
        window.opener = null;
        window.open('', '_self');
        window.close();
      }, 1000);
    } else {
      scrapValue.value = '';
      discardRemark.value = '';
      markScrapVisible.value = data.flag;
    }
  };

  // 获取废片原因配置
  const initScrapData = async () => {
    // 获取废片原因
    const res = await commonList();
    const { discardReasons, ...newRes } = res?.data;
    scrapList.value = discardReasons!;
    markScrapVisible.value = true;
  };

  // 提交弹窗右上角×关闭
  const handleCancel = () => {
    submitVisible.value = false;
  };
  return {
    markScrapVisible,
    submitVisible,
    sectionVisible,
    scrapList,
    scrapValue,
    discardRemark,
    handleMarkDesert,
    handleSubmit,
    handleMarkScrapVisible,
    handleSubmitVisible,
    handleSectionVisible,
    handleCancel
  }
}
